package com.tp;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends CustomWindow implements OnClickListener {
	// Activity activity;
	EditText username;
	EditText password;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		this.icon.setImageResource(R.drawable.authentication);
		this.title.setText("Đăng nhập");
		username = (EditText) findViewById(R.id.usename);
		password = (EditText) findViewById(R.id.password);

		View login = findViewById(R.id.login_button);
		login.setOnClickListener(this);
		View signup = (findViewById(R.id.signup));
		signup.setOnClickListener(this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		Intent i;
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_button:
			/*
			 * i = new Intent(this, Main.class); startActivity(i);
			 */
			checkLogin();// BinhDT 21/02

			break;
		case R.id.signup:
			i = new Intent(this, Signup.class);
			startActivity(i);
			break;

		}
	}

	public void checkLogin() {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("username", username
				.getText().toString()));
		postParameters.add(new BasicNameValuePair("password", password
				.getText().toString()));

		// String valid = "1";
		String response = null;
		JSONArray jArray;
		JSONObject json_data;
		int id_User;
		try {

			response = CustomHttpClient.executeHttpPost(Constant.host
					+ "/UserController/index", postParameters);
			jArray = new JSONArray(response);
			for (int i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_User = json_data.getInt("id_User");

				if (id_User > 0) {
					Toast.makeText(this, "Đăng nhập thành công",
							Toast.LENGTH_SHORT).show();
					Constant.user = id_User;
					startActivity(new Intent(this, Main.class));

				} else
					Toast.makeText(
							this,
							"Tài khoản hoặc mật khẩu không đúng. Nhập lại",
							Toast.LENGTH_SHORT).show();

			}
		} catch (Exception e) {
			Log.v("LOgin", e.toString());

		}
	}

}
